package com.joven.internet.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.joven.core.constant.ResultInfo;
import com.joven.core.constant.Status;
import com.joven.core.model.User;


import com.joven.core.service.ProductService1;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author joven_wong
 * 2021/5/27 8:49
 */
@RestController
@RequestMapping("/result")
public class TestController {

    @GetMapping("/hello")
    public ResultInfo<Object> testResult() {
        User user = new User();
        user.setName("Hello Test");
        return ResultInfo.success("Welcome to COFFEE House", user);
    }

    //服务引用
    //Dubbo默认（缺省）会在启动时检查依赖的服务是否可用，不可用时会抛出异常，阻止Spring初始化完成，以便上线时，能及早发现问题，默认check=true
    @Reference(check = false, version = "1.0.0", timeout = 100000, retries = 2, group = "test")
    ProductService1 productService;

    @GetMapping("/helloDubbo")
    public ResultInfo<Object> testDubbo() {
        List<User> infos = productService.getAllUsers();
        return ResultInfo.success(infos);
    }

    //若 blockHandler 和 fallback 都进行了配置，则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。
    // 若未配置 blockHandler、fallback 和 defaultFallback，则被限流降级时会将 BlockException 直接抛出。
    @GetMapping("/dubboMapper")
    @SentinelResource(value = "consumer-echo", blockHandler = "exceptionHandler", fallback = "echoFallBack")
    public ResultInfo<Object> testDubbo1(Long id) {
        User info = productService.getOneById(id);
        return ResultInfo.success(info);
    }

    // Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
    public ResultInfo<Object> exceptionHandler(Long id, BlockException ex) {
        ex.printStackTrace();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String message = "[exceptionHandler] Dubbo Sentinel Nacos Consumer:  - exception [" + ex.getMessage() + "]" + df.format(new Date());
        return ResultInfo.fail(message);
    }


    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数
    public ResultInfo<Object> echoFallBack(Long id) {
        String message = "[echoFallBack] Dubbo Sentinel Nacos Consumer:  - fallback [" + id + "]";
        return ResultInfo.fail(message);
    }

}
